<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>减碳达人排行榜管理</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 搜索 -->
        <el-form :inline="true" style="margin-top: 20px;">
            <el-form-item>
                <el-button size="small" @click="exportExcel">导出Excel</el-button>
            </el-form-item>
        </el-form>

        <!-- 列表 -->
        <el-table size="small" ref="multipleTable" :data="IntegralData" element-loading-text="拼命加载中">
            <el-table-column align="center" sortable type="index" label="序号" width="50px"></el-table-column>
            <el-table-column align="center" sortable prop="nickName" label="用户昵称"></el-table-column>
            <el-table-column align="center" sortable prop="phone" label="用户手机号"></el-table-column>
            <el-table-column align="center" label="操作" width="100" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="Zengsong(scope.row)">赠送优惠券</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 编辑界面 -->
        <el-dialog title="添加" :visible.sync="editFormVisiible" width="60%">
            <el-form label-width="120px">
                <el-form-item label="优惠券名称">
                    <el-select v-model="couponsId" placeholder="请选择优惠券名称" size="small">
                        <el-option v-for="item in optionsCou" :key="item.value" :label="item.label"
                            :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click='closeDialog()'>取消</el-button>
                <el-button size="small" type="primary" :loading="loading" @click="addData()">添加</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    getAdminLeaderboardList,
    sendCoupons,
    getCouponsList
} from "../../api/userMG";
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
export default {
    data() {
        return {
            loading: false,
            IntegralData: [],
            userName: '',
            phone: '',
            type: '',
            startTime: '',
            timestamp: '',
            options: [{
                value: 0,
                label: '新增'
            }, {
                value: 1,
                label: '扣除'
            }],
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            editFormVisiible: false,
            optionsCou: [],
            couponsId: ''
        }
    },
    created() {
        this.getdata();
        this.getCou()
    },
    methods: {
        // 添加
        addData() {
            this.loading = true
            sendCoupons({
                userId: this.userId,
                couponsId: this.couponsId
            }).then((res) => {
                this.loading = false;
                if (res.code == 200) {
                    this.editFormVisiible = false
                    this.$message.success(res.msg)
                    this.getdata(1)
                } else {
                    this.editFormVisiible = false
                    this.$message.error(res.msg);
                }
            })
        },
        // 打开编辑器
        Zengsong(row) {
            var userdata = JSON.parse(localStorage.getItem("userdata"))
            this.$prompt('请输入密码', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /^(?!(\s+$))/,
                inputErrorMessage: '不可以空数据提交!'
            }).then(({ value }) => {
                if (value === userdata.menuTwo) {
                    this.editFormVisiible = true
                    this.userId = row.id
                    this.couponsId = ''
                } else {
                    this.$message({
                        type: 'error',
                        message: '密码错误'
                    });
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '取消输入'
                });
            });
        },
        // 关闭编辑对话框
        closeDialog() {
            this.editFormVisiible = false
            this.$message({
                type: 'info',
                message: '已取消编辑'
            })
        },
        getCou() {
            getCouponsList({
                status: 0,
            }).then((res) => {
                this.loading = false;
                if (res.code != 200) {
                    this.$Message({
                        type: "info",
                        message: res.msg,
                    });
                } else {
                    res.data.list.forEach((item) => {
                        this.optionsCou.push({ label: item.name, value: item.id })
                    })
                    return;
                }
            })
        },
        exportExcel() {
            //转换成excel时，使用原始的格式
            var xlsxParam = { raw: true };
            let fix = document.querySelector(".el-table__fixed-right");
            let wb;
            //判断有无fixed定位，如果有的话去掉，后面再加上，不然数据会重复
            if (fix) {
                wb = XLSX.utils.table_to_book(
                    this.$refs.multipleTable.$el.removeChild(fix), xlsxParam
                );
                this.$refs.multipleTable.$el.appendChild(fix);
            } else {
                wb = XLSX.utils.table_to_book(this.$refs.multipleTable.$el, xlsxParam);
            }
            var wbout = XLSX.write(wb, {
                bookType: "xls",
                bookSST: true,
                type: "array",
            });
            try {
                // 如果是IE浏览器，使用Blob通过navigator.msSaveBlob保存
                if (navigator.msSaveBlob) {
                    navigator.msSaveBlob(new Blob([wbout], { type: 'application/octet-stream' }), '减碳达人列表.xlsx');
                } else {
                    // 在其他浏览器中使用file-saver保存文件
                    saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '减碳达人列表.xlsx');
                }
            } catch (e) {
                if (typeof console !== 'undefined') console.log(e, wbout);
            }
            return wbout;
        },
        // 积分
        jiFen: function (row) {
            if (row.type == 0) {
                return "新增"
            } else if (row.type == 1) {
                return "扣除"
            }
        },
        // 获取数据
        getdata() {
            this.loading = true;
            getAdminLeaderboardList().then((res) => {
                this.loading = false;
                if (res.code != 200) {
                    this.$Message({
                        type: "info",
                        message: res.msg,
                    });
                } else {
                    this.IntegralData = res.data.list;
                    return;
                }
            })
        },
    }
}
</script>

<style></style>